package com.caiyouxi.common.exception;

import com.caiyouxi.common.bean.ResData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一处理错误和返回
 * weichangyong
 *
 * @create 2017-08-31 16:10
 **/

@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 系统异常处理，比如：404,500
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResData defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        logger.error("", e);
        ResData resData = new ResData();
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            resData.setCode(ErrorCode.SYS_API_NOT_FOUND.getCode());
            resData.setMsg(ErrorCode.SYS_API_NOT_FOUND.getMsg());
        } else {
            resData.setCode(ErrorCode.SYS_BUSSINESS_ERROR.getCode());
            resData.setMsg(ErrorCode.SYS_BUSSINESS_ERROR.getMsg());
        }
        resData.setData("");
        return resData;
    }
}
